package com.llm.travel_agent_assistant.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.llm.travel_agent_assistant.dto.Result;
import com.llm.travel_agent_assistant.dto.UserDTO;
import com.llm.travel_agent_assistant.entity.User;
import com.llm.travel_agent_assistant.mapper.UserMapper;
import com.llm.travel_agent_assistant.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;
    
    @Resource
    private HttpServletRequest request;

    public Result register(User registryUser) {
        User user = userMapper.selectById(registryUser.getUserId());
        if (user != null) {
            return Result.fail("用户已经存在");
        }
        int insert = userMapper.insert(registryUser);
        if (insert > 0) {
            return Result.ok("注册成功");
        }
        return Result.fail("注册失败");
    }

    @Override
    public Result login(UserDTO userDTO) {
        QueryWrapper<User> wrapper = new QueryWrapper<User>()
                .eq("user_id", userDTO.getUserId());
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            return Result.fail("请先注册");
        }
        if (!user.getPassword().equals(userDTO.getPassword())) {
            return Result.fail("密码错误");
        }
        
        // 登录成功，设置session
        HttpSession session = request.getSession();
        session.setAttribute("userId", user.getUserId());
        session.setAttribute("userName", user.getUserName());
        
        return Result.ok(user);
    }

    @Override
    public Result logout(String userId) {
        // 清除session
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return Result.ok("退出成功");
    }
}
